<template>
  <div class="designer-container">
    <div  ref="canvas" style="flex: 1; border: 1px solid #e4e7ed;"></div>
    <div style="display: flex; height: 600px;">
      <div  ref="canvas" style="flex: 1; border: 1px solid #e4e7ed;"></div>
      <div ref="propertiesPanel" style="width: 300px; border-left: 1px solid #e4e7ed;"></div>
    </div>
    <div class="button-group">
      <el-button type="primary" @click="saveProcess">保存流程</el-button>
      <el-button type="success" @click="resetCanvas">重置流程</el-button>
    </div>
  </div>
</template>

<script>
import BpmnModeler from 'bpmn-js/lib/Modeler';
import { Message } from 'element-ui';
import request from '@/utils/request';
import propertiesPanelModule from 'bpmn-js-properties-panel';
import camundaPropertiesProvider from 'bpmn-js-properties-panel/lib/provider/camunda';
import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda.json'; // 关键元数据导入

// 样式导入（确保路径正确）
import 'bpmn-js/dist/assets/diagram-js.css';
import 'bpmn-js-properties-panel/dist/assets/bpmn-js-properties-panel.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
export default {
  data() {
    return {
      bpmnModeler: null,
      initialXml: `<?xml version="1.0" encoding="UTF-8"?>
        <definitions
          xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
          xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
          xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC"
          xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI"
          xmlns:camunda="http://camunda.org/schema/1.0/bpmn"
          id="Definitions_1"
          targetNamespace="http://www.activiti.org/processdef">

          <process id="leaveProcess" name="请假流程" isExecutable="true">
            <startEvent id="start" name="开始" />
            <userTask
              id="applyTask"
              name="请假申请"
              camunda:assignee="employee"
            />
            <endEvent id="end" name="结束" />
            <sequenceFlow id="flow1" sourceRef="start" targetRef="applyTask" />
            <sequenceFlow id="flow2" sourceRef="applyTask" targetRef="end" />
          </process>

          <bpmndi:BPMNDiagram id="BPMNDiagram_1">
            <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="leaveProcess">
              <bpmndi:BPMNShape id="start_di" bpmnElement="start">
                <omgdc:Bounds x="100" y="100" width="30" height="30"/>
              </bpmndi:BPMNShape>
              <bpmndi:BPMNShape id="applyTask_di" bpmnElement="applyTask">
                <omgdc:Bounds x="200" y="80" width="100" height="80"/>
              </bpmndi:BPMNShape>
              <bpmndi:BPMNShape id="end_di" bpmnElement="end">
                <omgdc:Bounds x="350" y="100" width="30" height="30"/>
              </bpmndi:BPMNShape>
              <bpmndi:BPMNEdge id="flow1_di" bpmnElement="flow1">
                <omgdi:waypoint x="130" y="115"/>
                <omgdi:waypoint x="200" y="120"/>
              </bpmndi:BPMNEdge>
              <bpmndi:BPMNEdge id="flow2_di" bpmnElement="flow2">
                <omgdi:waypoint x="300" y="120"/>
                <omgdi:waypoint x="350" y="115"/>
              </bpmndi:BPMNEdge>
            </bpmndi:BPMNPlane>
          </bpmndi:BPMNDiagram>
        </definitions>`
    };
  },

  mounted() {
    this.initModeler();
  },

  methods: {
    initModeler() {
      this.bpmnModeler = new BpmnModeler({
        container: this.$refs.canvas,
        // 注册Camunda元数据（解决unknown type错误）
        moddleExtensions: {
          camunda: camundaModdleDescriptor
        },
        additionalModules: [
          propertiesPanelModule,
          camundaPropertiesProvider // 启用Camunda属性面板
        ],
        propertiesPanel: {
          parent: this.$refs.propertiesPanel // 绑定属性面板容器
        },
        palette: {
          entries: (entries) => entries.filter(entry => !entry.action?.startsWith('create.group'))
        }
      });

      this.loadInitialProcess();
    },

    loadInitialProcess() {
      this.bpmnModeler.importXML(this.initialXml)
        .then(() => {
          Message.success('初始流程加载成功！');
          this.bpmnModeler.get('canvas').zoom('fit-viewport');
        })
        .catch(err => {
          console.error('加载失败:', err);
          Message.error('初始流程加载失败，请检查 XML 格式');
        });
    },

    async saveProcess() {

      try {
        const { xml } = await this.bpmnModeler.saveXML({ format: true });
          console.log('导出的XML:', xml); // 检查是否包含 <userTask activiti:assignee="employee"/>
        const res = await request({
          url: '/t/deploy',
          method: 'post',
          data: {
            processKey: 'leaveProcess',
            bpmnXml: xml
          }
        });
        console.log(res)
      } catch (err) {
        Message.error('保存失败，请检查网络或设计内容');
        console.error(err);
      }
    },

    resetCanvas() {
      this.bpmnModeler.importXML(this.initialXml);
      Message.success('流程已重置');
    }
  },

  beforeDestroy() {
    this.bpmnModeler?.destroy();
  }
};
</script>

<style scoped>
.designer-container {
  padding: 20px;
  background: #fff;
}
</style>
